/**
 * Copyright (c) 2014,Egret-Labs.org
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Egret-Labs.org nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

class Main extends egret.DisplayObjectContainer{

    /**
     * 加载进度界面
     */
    private loadingView:LoadingUI;

    private  clickNum:number;
    private  leaveTime:number;
    private  totalNum:number;
    private totalTime:number;

    private  myScore:egret.TextField;
    private  myTime:egret.TextField;

    private  myTimer:egret.Timer;
    private  handTimer:egret.Timer;
    private  cartTimer:egret.Timer;
    private daoTimer:egret.Timer;
    private floatTimer:egret.Timer;
    //private daoTimer1:egret.Timer;

    private  gifts:egret.Bitmap[];

    private cart:egret.Bitmap;
    private arrow:egret.Bitmap;
    private arrow_small:egret.Bitmap;
    private dao:egret.Bitmap;
    private successPanel :SuccessPanel;
    private failPanel :FailPanel;
    private isWin:number;
    private currentHand:number;
    private currentCart:number;
    private totalHand:number;

    private currentDao:number;
    private currentDao1:number;
    private totalDao:number;
    private totalDao2:number;
    private totalClickFrames;

    private hand:egret.Bitmap;

    public static stageH : number;

    private gameOn:number;

    private base_price:number;

    private is_last:number;

    private btnStart:egret.Bitmap;


    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
    }

    private onAddToStage(event:egret.Event){
        //设置加载进度界面
        this.loadingView  = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.loadConfig("resource/resource.json","resource/");
    }
    /**
     * 配置文件加载完成,开始预加载preload资源组。
     */
    private onConfigComplete(event:RES.ResourceEvent):void{
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceProgress,this);
        RES.loadGroup("preload");
    }
    /**
     * preload资源组加载完成
     */
    private onResourceLoadComplete(event:RES.ResourceEvent):void {
        if(event.groupName=="preload"){
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceProgress,this);
            this.createGameScene();
        }
    }
    /**
     * preload资源组加载进度
     */
    private onResourceProgress(event:RES.ResourceEvent):void {
        if(event.groupName=="preload"){
            this.loadingView.setProgress(event.itemsLoaded,event.itemsTotal);
        }
    }

    private textContainer:egret.Sprite;
    /**
     * 创建游戏场景
     */
    private createGameScene():void{
        this.clickNum = 0;
        this.leaveTime = 0;
        this.totalNum = 50;
        this.totalTime = 800;
        this.base_price = 600;
        this.gifts = [];
        var sky:egret.Bitmap = this.createBitmapByName("bgImage");
        this.addChild(sky);
        var stageW:number = this.stage.stageWidth;
        var stageH:number = this.stage.stageHeight;
        Main.stageH = this.stage.stageHeight;

        sky.width = stageW;
        sky.height = stageH;



        this.cart = this.createBitmapByName("cart_1");
        this.addChild(this.cart);
        this.cart.anchorX = this.cart.anchorY = 0.5;
        this.cart.x = stageW/2;
        this.cart.y = stageH/2-60;
        this.cart.scaleX = .8;
        this.cart.scaleY = .8;

        this.hand = this.createBitmapByName("hand1");
        this.addChild(this.hand);
        this.hand.anchorY =this.hand.anchorX= 1;
        this.hand.x = stageW + 18;
        this.hand.y = stageH +30;
        this.hand.scaleX = this.hand.scaleY = 1;

        this.dao  = this.createBitmapByName("dao11");
        this.addChild(this.dao);
        this.dao.anchorX = this.dao.anchorY = .5;
        this.dao.x = stageW - 70;
        this.dao.y = 50;
        this.dao.scaleX = this.dao.scaleY = 1;
        this.dao.touchEnabled = true;
        this.dao.addEventListener(egret.TouchEvent.TOUCH_TAP,this.clickDao,this);//点击按钮开始游戏
        //this.swapChildren(this.dao,this.cart);

        var label1:egret.TextField = new egret.TextField();
        label1.width = 110;
        label1.text = "我的得分：";
        label1.size = 20;
        label1.textColor = 0xff6600;
        label1.textAlign = egret.HorizontalAlign.LEFT;
        label1.x = 20;
        label1.y = 10;
        //this.addChild(label1);

        this.myScore= new egret.TextField();
        this.myScore.width = 50;
        this.myScore.textColor = 0xffffff;
        this.myScore.textAlign = egret.HorizontalAlign.LEFT;
        this.myScore.text =  " " + this.clickNum;
        this.myScore.size = 20;
        this.myScore.x = 120;
        this.myScore.y = 10;
        //this.addChild(this.myScore);

        var label2:egret.TextField = new egret.TextField();
        label2.width = 110;
        label2.text = "剁手时间:";
        label2.size = 20;
        label2.textColor = 0xff6600;
        label2.textAlign = egret.HorizontalAlign.LEFT;
        label2.x = 20;
        label2.y = 10;
       // this.addChild(label2);

        this.myTime = new egret.TextField();
        this.myTime.width = 800;
        this.myTime.textColor = 0xffffff;
        this.myTime.textAlign = egret.HorizontalAlign.LEFT;
        this.myTime.text = " " +  (this.leaveTime /100) + " s";
        this.myTime.x = 120;
        this.myTime.y = 10;
        this.myTime.size = 20;
        //this.addChild(this.myTime);

        this.myTimer = new egret.Timer(10,0);
        this.myTimer.addEventListener(egret.TimerEvent.TIMER,this.timerFunc,this);
        //this.myTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE,this.timerComFunc,this);
        //this.myTimer.start();
       //this.myTimer.stop();

        this.handTimer = new egret.Timer(45,0);
        this.handTimer.addEventListener(egret.TimerEvent.TIMER,this.handFunc,this);

        this.daoTimer = new egret.Timer(45,0);
        this.daoTimer.addEventListener(egret.TimerEvent.TIMER,this.daoFunc,this);

        //this.daoTimer1 = new egret.Timer(45,0);
        //this.daoTimer1.addEventListener(egret.TimerEvent.TIMER, this.dao1Func,this);

        this.cartTimer = new egret.Timer(500,20);
        this.cartTimer.addEventListener(egret.TimerEvent.TIMER,this.cartFunc,this);

        this.floatTimer = new egret.Timer(2000,0);
        this.floatTimer.addEventListener(egret.TimerEvent.TIMER,this.floatFunc,this);


        this.arrow =  this.createBitmapByName("arrow");
        this.arrow.x = stageW - 150;
        this.arrow.y = 200;
        this.addChild(this.arrow);
        this.arrow.scaleX = this.arrow.scaleY = .2;

        this.arrowAnimation();

        var tishi:egret.Bitmap = this.createBitmapByName("tishi");
        tishi.x = 5;
        tishi.y = 0.156 * stageH + 30;
        tishi.scaleX = tishi.scaleY = .7;
        this.addChild(tishi);

        this.arrow_small = this.createBitmapByName("arrow_small");
        this.arrow_small.x = 240;
        this.arrow_small.y = 0.156 * stageH + 36;
        this.arrow_small.scaleX = this.arrow_small.scaleY = .7;
        this.addChild(this.arrow_small);

        this.arrow_show();


        this.isWin = 0;

        this.successPanel = new SuccessPanel();
        this.successPanel.addEventListener("shareEvent" , this.doShare , this);
        this.successPanel.addEventListener("replayEvent" , this.doRestart , this);

        this.failPanel = new FailPanel();

        this.failPanel.addEventListener("shareEvent" , this.doShare , this);
        this.failPanel.addEventListener("replayEvent" , this.doRestart , this);

        this.btnStart = this.createBitmapByName("btnStart");//开始按钮
        this.btnStart.x = (stageW-this.btnStart.width)/2;//居中定位
        this.btnStart.y = (stageH *0.64 +288 - this.btnStart.height)/2 + 20;
        this.btnStart.touchEnabled = true;//开启触碰
        this.btnStart.addEventListener(egret.TouchEvent.TOUCH_TAP,this.gameStart,this);//点击按钮开始游戏
        this.addChild(this.btnStart);

        this.currentHand = 1;
        this.totalHand = 4;
        this.currentDao = 1;
        this.currentDao1 = 1;
        this.totalClickFrames = 0;
        this.totalDao = 7;
        this.totalDao2 = 9;
        this.gameOn = 0;
        this.currentCart =0;
        this.handTimer.start();
        this.daoTimer.start();
        this.floatTimer.start();
        this.is_last = 0;
    }

    private gameStart(event:egret.TouchEvent){
        this.removeChild(this.btnStart);
    }

    private cartFunc(){
        this.currentCart++;
        if(this.currentCart>20){
            this.currentCart = 20;
        }
        this.cart.texture = RES.getRes("cart_"+this.currentCart);
    }

    private doShare(event:egret.Event){
        share(1,this.leaveTime/100,this.successPanel.title_strs);
    }
    private doRestart(event:egret.Event){
        this.addChild(this.arrow);
        this.dao.texture = RES.getRes("dao11");
        this.dao.y = 50;
        /*
        this.removeChild(this.cart);
        this.cart = this.createBitmapByName("cart_1");
        this.addChild(this.cart);
        this.cart.anchorX = this.cart.anchorY = 0.5;
        this.cart.x = this.stage.stageWidth/2;
        this.cart.y = this.stage.stageHeight/2-60;
        this.cart.scaleX = .8;
        this.cart.scaleY = .8;

        this.swapChildren(this.dao,this.cart);
        */
        this.currentCart =0;
        this.cart.texture = RES.getRes("cart_1");

        this.game_start();

    }

    private timerFunc()
    {
       this.leaveTime = this.leaveTime + 1;
        this.myTime.text = " " + (this.leaveTime/100) +" s";
    }

    private floatFunc(){
        if(this.gameOn){
            var textmondy:egret.TextField = new egret.TextField();
            textmondy.width = 300;
            textmondy.textColor = 0xffff00;
            textmondy.textAlign = egret.HorizontalAlign.LEFT;
            textmondy.text = this.base_price + "元没了";
            this.base_price = this.base_price +Math.floor(10*Math.random())*100;
            if(this.base_price>6000){
                this.base_price = 600;
            }
            textmondy.anchorX = .5;
            textmondy.x = 200;
            textmondy.y = this.stage.stageHeight;
            textmondy.size = 35;
            this.addChild(textmondy);
            var tw:egret.Tween = egret.Tween.get(textmondy);
            tw.to({"y":textmondy.y - 300,"alpha":.0},1500);
            //tw.call(removeMe, this);
            var removeMe = function(){
                textmondy.parent.removeChild(textmondy);
            }
        }
    }

    private timerComFunc(){
        console.log("时间到！");
        if(this.leaveTime <= this.totalTime){
            this.isWin = 1;
            console.log("成功~");
            this.myTimer.reset();
            this.game_succ();

        }else{
            console.log("失败~");
            this.isWin = 0;
            //this.game_fail();
            //this.game_result();
            this.game_succ();
        }
    }

    private game_result(){
        this.successPanel.x = (this.stage.stageWidth - this.successPanel.width)/2;
        this.successPanel.score(this.leaveTime/100,this.isWin);
        this.addChild(this.successPanel);
        showme(this.leaveTime/100);
        return;
    }

    private game_succ()
    {
        //300/6 = 50;
        var tw = egret.Tween.get(this.dao);
        var y0 = this.dao.y;
        var y1 = this.dao.y + 45;
        tw.to({"y":y1}, 140);
        var total = 10;
        var daoTmp = this.dao;
        var main = this;
        var next = function(){
            if(total<=0){
                console.log("刀切到手了~~！");
                var timer:egret.Timer = new egret.Timer(500,1);
                timer.addEventListener(egret.TimerEvent.TIMER,main.game_result,main);
                timer.start();
                return;
            }
            total = total -1;
            var tw_next = egret.Tween.get(daoTmp);
            var yTmp = daoTmp.y  + 35;
            tw_next.to({"y":yTmp}, 14 * total);
            tw_next.call(next,this);
        }
        tw.call(next,this);
        this.gameOn = 0;
        //this.currentHand = 1;
    }

    private game_fail()
    {
        this.failPanel.x = (this.stage.stageWidth - this.failPanel.width)/2;
        this.failPanel.score(this.clickNum);
        this.addChild(this.failPanel);
        this.gameOn = 0;
        //this.currentHand = 1;
    }

    private game_start(){
        this.clickNum = 0;
        this.leaveTime = 0;
        this.isWin  =0;
        this.totalClickFrames =0;
        this.base_price = 600;
        this.is_last = 0;
        if(this.successPanel.parent)
        {
            this.removeChild(this.successPanel);
        }
        if(this.failPanel.parent)
        {
            this.removeChild(this.failPanel);
        }
        this.myTime.text = " " +  (this.leaveTime /100)+" s";
        this.myScore.text =  " " + this.clickNum;
        this.handTimer.start();
    }

    private clickDao(event:egret.TouchEvent){
        if(this.clickNum >=this.totalNum){
            if(this.is_last ==0){
                this.totalClickFrames =9;
                this.currentDao =0;
                this.is_last = 1;
                var timer:egret.Timer = new egret.Timer(1300,1);
                var _curSound:egret.Sound = RES.getRes("click_sound");
                timer.addEventListener(egret.TimerEvent.TIMER,function(evt:Event){
                    _curSound.play();},null);
                timer.start();
                return;
            }

            return;
        }else{
            var _curSound:egret.Sound = RES.getRes("over_sound");
            _curSound.play();
            if(this.clickNum< this.totalNum - 5){
                this.totalClickFrames += 7;
            }else{
                this.totalClickFrames += 9;
            }

            if(this.clickNum == 0){
                this.removeChild(this.arrow);
                this.myTimer.start();
                this.cartTimer.start();
                this.clickNum ++;
                this.myScore.text =  "" + this.clickNum;
                this.gameOn = 1;
                return;
            }
            this.clickNum = this.clickNum + 1;
            this.myScore.text =  "" + this.clickNum;
            console.log(this.clickNum);

        }



        //if(this.clickNum<=20){
            /*
            this.removeChild(this.cart);

            this.cart = this.createBitmapByName("cart_"+this.clickNum);
            this.addChild(this.cart);
            this.cart.anchorX = this.cart.anchorY = 0.5;
            this.cart.x = this.stage.stageWidth/2;
            this.cart.y = this.stage.stageHeight/2-60;
            this.cart.scaleX = .8;
            this.cart.scaleY = .8;
            this.swapChildren(this.dao,this.cart);
            */
        //}
        /*
        var gift_nu:number = Math.floor(4*Math.random());
        var gift:egret.Bitmap = this.createBitmapByName("gift_"+gift_nu);
        gift.anchorX = gift.anchorY = 0.5;
        gift.x = this.stage.stageWidth /2 -50 + 60 * Math.random();
        gift.y = this.stage.stageHeight /2 - 60 + 40 * Math.random();
        gift.scaleX = gift.scaleY = .5;
        this.addChild(gift);
        this.swapChildren(gift,this.cart);
        this.gifts.push(gift);
        */
    }

    private createBitmapByName(name:string):egret.Bitmap {
        var result:egret.Bitmap = new egret.Bitmap();
        var texture:egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }

    private handFunc()
    {
        //if(this.gameOn>0){
            if(this.currentHand> this.totalHand){
                this.currentHand = 1;
            }
            this.hand.texture = RES.getRes("hand"+this.currentHand);
            this.currentHand ++;
        //}
    }

    private daoFunc()
    {
        if(this.gameOn>0){
            console.log("ieiei");
            if(this.totalClickFrames<=0){
                console.log("ieiei22");
                this.totalClickFrames =0;
                return;
            }
            this.totalClickFrames--;
            if(this.currentDao> this.totalDao){
                this.currentDao = 1;
            }
            if(this.totalClickFrames > 20 || this.clickNum>= this.totalNum - 5 ){
                this.dao.texture = RES.getRes("dao2"+this.currentDao);
            }else{
                this.dao.texture = RES.getRes("dao1"+this.currentDao);
            }

            this.currentDao ++;
            if(this.totalClickFrames == 0){
                this.dao.texture = RES.getRes("dao11");
            }

            console.log("ieieiff");
            if(this.totalClickFrames ==0 && this.clickNum >= this.totalNum){
                console.log("ieieiggg");
                this.dao.texture = RES.getRes("dao_t");
                this.handTimer.stop();
                if(this.leaveTime <= this.totalTime){
                    this.isWin = 1;
                    console.log("成功~");
                    this.myTimer.reset();
                    this.game_succ();

                }else{
                    console.log("失败~");
                    this.isWin = 0;
                    this.gameOn = 0;
                    this.myTimer.reset();
                    //this.game_fail();
                   // this.game_result();
                    this.game_succ();
                }
            }
        }
    }

    private dao1Func(){
        if(this.currentDao1> this.totalDao2){
            this.currentDao1 = 1;
        }
        this.dao.texture = RES.getRes("dao2"+this.currentDao1);
        this.currentDao1 ++;
    }

    private arrow_show():void
    {
        var arrowTmp :egret.Bitmap = this.arrow_small;

        var hide:Function = function(){
            var tw = egret.Tween.get(arrowTmp);
            tw.to({"alpha": 0},500);
            tw.call(shine,this);
        }
        var shine:Function = function () {
             var tw = egret.Tween.get(arrowTmp);
            tw.to({"alpha":1 },500);
            tw.call(hide,this);
        }
        hide();
    }

    private arrowAnimation():void{
        var arrowTmp :egret.Bitmap = this.arrow;

        var goLeft:Function = function(){
            var tw = egret.Tween.get(arrowTmp);
            var arrowX:number = arrowTmp.x - 30;
            var arrowY:number = arrowTmp.y - 10;
            tw.to({"x":arrowX,"y":arrowY },500);
            tw.call(goRight,this);
        }
        var goRight:Function = function () {
            var tw = egret.Tween.get(arrowTmp);
            var arrowX:number = arrowTmp.x + 30;
            var arrowY:number = arrowTmp.y + 10;
            tw.to({"x":arrowX,"y":arrowY },500);
            tw.call(goLeft,this);
        }
        goLeft();
    }
    /**
     * 描述文件加载成功，开始播放动画
     */
    private startAnimation(result:Array<any>):void{
        var textContainer:egret.Sprite = this.textContainer;
        var count:number = -1;
        var self:any = this;
        var change:Function = function() {
            count++;
            if (count >= result.length) {
                count = 0;
            }
            var lineArr = result[count];

            self.changeDescription(textContainer, lineArr);

            var tw = egret.Tween.get(textContainer);
            tw.to({"alpha":1}, 200);
            tw.wait(2000);
            tw.to({"alpha":0}, 200);
            tw.call(change, this);
        }

        change();
    }
    /**
     * 切换描述内容
     */
    private changeDescription(textContainer:egret.Sprite, lineArr:Array<any>):void {
        textContainer.removeChildren();
        var w:number = 0;
        for (var i:number = 0; i < lineArr.length; i++) {
            var info:any = lineArr[i];
            var colorLabel:egret.TextField = new egret.TextField();
            colorLabel.x = w;
            colorLabel.anchorX = colorLabel.anchorY = 0;
            colorLabel.textColor = parseInt(info["textColor"]);
            colorLabel.text = info["text"];
            colorLabel.size = 40;
            textContainer.addChild(colorLabel);

            w += colorLabel.width;
        }
    }
}


